package com.gitee.urick.union.utils;


import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;

import java.util.HashMap;

/**
 * <p>
 * 响应结果封装 工具类
 * </p>
 *
 * @author uRick 2020-04-13
 * @since 1.0
 */
@Setter
@Getter
public class Result<T> {
    private boolean success;
    /**
     * 状态码
     */
    private int code;
    /**
     * 状态消息
     */
    private String msg;
    /**
     * code为200时，返回
     */
    private T data;

    private Result() {
    }

    private Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private static <T> Result<T> success(String msg) {
        return builder(HttpStatus.OK.value(), msg);
    }

    public static <T> Result<T> success() {
        return success(MsgInfo.SUCCESS.value());
    }

    public static <T> Result<T> error() {
        return error(HttpStatus.INTERNAL_SERVER_ERROR, MsgInfo.ERROR);
    }

    public static <T> Result<T> error(HttpStatus code) {
        return error(code, code.getReasonPhrase());
    }

    public static <T> Result<T> error(String msg) {
        return error(HttpStatus.INTERNAL_SERVER_ERROR, msg);
    }

    public static <T> Result<T> error(MsgInfo msg) {
        return error(HttpStatus.INTERNAL_SERVER_ERROR, msg);
    }

    public static <T> Result<T> error(HttpStatus status, MsgInfo msg) {
        return error(status, msg.value());
    }

    public static <T> Result<T> error(HttpStatus status, String msg) {
        return builder(status.value(), msg);
    }

    public static <T> Result<T> error(int status, String msg) {
        return builder(status, msg);
    }

    public static <T> Result<T> success(T data) {
        Result<T> success = success();
        success.setData(data);
        return success;
    }

    private static <T> Result<T> builder(int code, String msg) {
        return new Result<>(code, msg);
    }


    public static DefaultData newDefaultData() {
        return new DefaultData();
    }

    public static DefaultData newDefaultData(int capacity) {
        return new DefaultData(capacity);
    }

    /**
     * 默认响应数据实体
     */
    public static class DefaultData extends HashMap<String, Object> {
        public DefaultData() {
        }

        public DefaultData(int initialCapacity) {
            super(initialCapacity);
        }

        @Override
        public DefaultData put(String key, Object value) {
            super.put(key, value);
            return this;
        }
    }

    public boolean getSuccess() {
        return this.code == HttpStatus.OK.value();
    }
}
